%Down biased (H reference local) transfn 
% Referece Sims et al 1971  Geophysics
% importance - the simple matrix notations l
% uses the matrix notations
%CHECKED WITH GEOTOOLS OK 30.4.3
% added variance -> 24.11.4
% 
function[tf]=tf_dn_new(SPMatrix,ProcDef,nfrq), 

A = size(SPMatrix);
if length(A) == 4,
    SPMatrix = squeeze(SPMatrix(nfrq,:,:,:)); % the spm for a single frequency nfrq
end;

A = size(SPMatrix);

if length(A) == 2,
   data(:,:)=SPMatrix;
   [EH,HH]=getmat(data);
   Z = EH/HH; % inverse of admittance = impedance
   tf(1)=Z(1,2);% boring !! but i have to do this
   tf(2)=Z(2,1);
   tf(3)=Z(1,1);
   tf(4)=Z(2,2);
elseif length(A)==3,
   for i =1:A(1),
      data(:,:)=SPMatrix(i,:,:);
      [EH,HH]=getmat(data);
   Z = EH/HH;
   tf(i,1)=Z(1,2);% boring !! but i have to do this
   tf(i,2)=Z(2,1);
   tf(i,3)=Z(1,1);
   tf(i,4)=Z(2,2);
   
    c1 = cohe(tf(i,3),tf(i,1),data,'Ex'); % predictive coherency ex-hxhy
	c2 = cohe(tf(i,2),tf(i,4),data,'Ey');% predictive coherency ey-hxhy
    dof = ProcDef.TLRad1(nfrq)*2; % degrees of freedom = frequency band width
	[tf(i,7),tf(i,5)] = BivError(c1,dof,data,'Ex'); % bivaraite error
	[tf(i,6),tf(i,8)] = BivError(c2,dof,data,'Ey');
end;
 
end;
   
   
   
%helper function


function[EH,HH]=getmat(data),

j = sqrt(-1);

HxHx = data(1,1);
HyHy = data(2,2);

HxHy = data(2,1) - j*data(1,2);
HyHx = conj(HxHy);
HxEx = data(4,1) - j*data(1,4);
ExHx = conj(HxEx);
HxEy = data(5,1) - j*data(1,5);
EyHx = conj(HxEy);
ExHy = data(4,2) + j*data(2,4);
EyHx = conj(HxEy);
ExHy = data(4,2) + j*data(2,4);
HyEy = data(5,2) - j*data(2,5);
EyHy = conj(HyEy);


EH=[ExHx ExHy;EyHx EyHy];
HH=[HxHx HxHy;HyHx HyHy];

